package com.china.produce.netty.learning.server.handler.rpc;

import com.china.produce.netty.learning.message.rpc.RpcRequestMessage;
import com.china.produce.netty.learning.message.rpc.RpcResponseMessage;
import com.china.produce.netty.learning.server.service.rpc.ServicesFactory;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import java.lang.reflect.Method;

/**
 * @ClassName
 * @Author niujie
 * @Version
 * @Description
 * @CreateTime 2024/9/22
 */
@ChannelHandler.Sharable
public class RpcRequestMessageHandler extends SimpleChannelInboundHandler<RpcRequestMessage> {
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, RpcRequestMessage msg) throws Exception {
        RpcResponseMessage responseMessage = new RpcResponseMessage();
        responseMessage.setSequenceId(msg.getSequenceId());

        String interfaceName = msg.getInterfaceName();

        Class<?> clazz = Class.forName(interfaceName);
        Method method = clazz.getMethod(msg.getMethodName(), msg.getParameterTypes());
        Object result = method.invoke(ServicesFactory.getServiceImpl(clazz), msg.getParameterValue());
        System.out.println(" interfaceName " + interfaceName + " value " + msg.getParameterValue() + " result " + result);
        responseMessage.setReturnValue(result);

        ctx.channel().writeAndFlush(responseMessage);
    }
}
